package member.order.service;

import m.common.model.util.ModelQueryList;
import m.common.model.util.QueryCondition;
import m.common.service.Service;
import m.system.db.DataRow;
import m.system.db.SqlBuffer;
import member.base.model.StoreInfo;
import member.order.model.OrderCollect;

public class OrderCollectService extends Service {
    /**
     * 更新订单汇总
     */
    public void update(String storeOid, String accountDate) throws Exception {
        OrderCollect model= ModelQueryList.getModel(OrderCollect.class,new String[]{"*"},
            QueryCondition.and(
                QueryCondition.eq("inputStore.oid",storeOid),
                QueryCondition.eq("accountDate", accountDate)
            )
        );
        if(null==model){
            model=new OrderCollect();
            model.setInputStore(new StoreInfo());
            model.getInputStore().setOid(storeOid);
            model.setAccountDate(accountDate);
        }
        DataRow dr=new SqlBuffer()
            .append("select")
            .append("sum(1) doneNum,sum(pay_amount) doneAmount,")
            .append("sum(preferential_amount) preferentialAmount,sum(-member_day_amount) memberDayAmount")
            .append("from o_order_info")
            .append("where status='Y' and input_store_oid=?", storeOid)
            .append("and date_format(account_date,'%Y-%m-%d')=?",accountDate)
            .queryFirstRow();
        if(null!=dr) {
            model.setOrderNum(dr.get(Integer.class,"doneNum"));
            model.setOrderAmount(dr.get(Double.class,"doneAmount"));
            model.setPreferentialAmount(dr.get(Double.class,"preferentialAmount"));
            model.setMemberDayAmount(dr.get(Double.class,"memberDayAmount"));
        }
        dr=new SqlBuffer()
            .append("select")
            .append("sum(1) doneNum,sum(pay_amount) doneAmount")
            .append("from o_member_recharge")
            .append("where status='Y' and input_store_oid=?", storeOid)
            .append("and date_format(account_date,'%Y-%m-%d')=?",accountDate)
            .queryFirstRow();
        if(null!=dr) {
            model.setRechargeNum(dr.get(Integer.class,"doneNum"));
            model.setRechargeAmount(dr.get(Double.class,"doneAmount"));
        }
        saveModel(model);
    }
}
